﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reactive.Linq;
using System.Windows;
using Caliburn.Micro;
using Microsoft.Phone.Tasks;
using Wulong.Phone.Qiushi.Helpers;
using Wulong.Phone.Qiushi.i18n;
using Wulong.Phone.Qiushi.Models;


namespace Wulong.Phone.Qiushi.ViewModels
{
    public class QiushiListViewModel :
        BusyIndicatorViewModelBase,
        IHandle<TaskCompleted<EmailComposeTask>>,
        IHandle<TaskCompleted<SmsComposeTask>>
    {
        private const int DefaultItemsPerPage = 20;

        public QiushiListViewModel(
            IEventAggregator events,
            INavigationService navigationService)
        {
            ItemsPerPage = DefaultItemsPerPage;
            Page = 1;
            _events = events;
            _navigationService = navigationService;
            _qiushiItems = new ObservableCollection<QiushiItem>();
        }

        protected override void OnActivate()
        {
            _events.Subscribe(this);
            base.OnActivate();
        }

        protected override void  OnViewReady(object view)
        {
                 
            base.OnViewReady(view);        
            if(_qiushiItems.Count()==0)
                RefreshList();
        }

        protected override void OnDeactivate(bool close)
        {
            _events.Unsubscribe(this);
            base.OnDeactivate(close);
            SelectedItem = null;
        }

        private string _section;
        public string Section { get { return _section; } 
            set 
                { 
                    if (value.Equals(_section)) return;
                    _section = value;
                } 
        }

        public int Page { get; set; }

        public int ItemsPerPage { get; set; }

        public int CountOfItemsUpdated { get; set; }

        public ObservableCollection<QiushiItem> _qiushiItems;

        public IEnumerable<QiushiItem> QiushiItems
        {
            get { return _qiushiItems; }
        }

        private bool _canLoadMore;

        public bool CanLoadMore
        {
            get { return _canLoadMore; }
            set
            {
                if (_canLoadMore == value)
                    return;
                _canLoadMore = value;
                NotifyOfPropertyChange(() => CanLoadMore);
            }
        }

        private QiushiItem _selectedItem;

        public QiushiItem SelectedItem
        {
            get { return _selectedItem; }
            set
            {
                if (_selectedItem == value)
                    return;
                _selectedItem = value;
                NotifyOfPropertyChange(() => SelectedItem);
            }
        }

        
        public void LoadMore()
        {
            if (IsBusy)
                return;
            IsBusy = true;
            CanLoadMore = false;

            _subject = QiushiMapper.GetObservableItems(Section, ItemsPerPage, Page * ItemsPerPage)
                .ObserveOnDispatcher()
                .Finally(() => { IsBusy = false; })
                .Subscribe(item =>
                               {
                                   if (IsContained(item.Id)) return;
                                   CountOfItemsUpdated += 1;
                                   _qiushiItems.Add(item);
                               },
                           DoAfterException,
                           DoAfterCompleted)
                ;
        }

        public void RefreshList()
        {
            if (IsBusy)  return;
            IsBusy = true;
            CanLoadMore = false;

            _subject = QiushiMapper.GetObservableItems(Section, ItemsPerPage)
                .ObserveOnDispatcher()                
                .Finally(() => { IsBusy = false; })
                .Subscribe(item =>
                               {
                                   if (IsContained(item.Id)) return;
                                   CountOfItemsUpdated += 1;
                                   _qiushiItems.Insert(CountOfItemsUpdated - 1, item);
                               },
                           DoAfterException,
                           DoAfterCompleted)
                ;
        }

        private bool IsContained(int id)
        {
            return _qiushiItems.Any(item => id == item.Id);
        }

        private void DoAfterException(Exception ex)
        {
            MessageBox.Show(AppResources.Ex_Network_Down_Message + "\r\n" + ex.Message,
                            AppResources.Ex_Error_Title,
                            MessageBoxButton.OK);
            --Page; //restore the page to original
        }

        private void DoAfterCompleted()
        {
            if (CountOfItemsUpdated > 0)
            {
                MessageHelper.ShowUpdateMessage(
                    DisplayName,
                    AppResources.VM_QiushiList_ToastMessage,
                    CountOfItemsUpdated);
                CountOfItemsUpdated = 0;
                Page++; //preparing for "load more" button
            }
            CanLoadMore = true;
        }

        public void NavigateToCommentsView(QiushiItem item)
        {
            _navigationService.UriFor<CommentsViewModel>()
                .WithParam(x => x.QiushiContent, item.Content)
                .WithParam(x => x.Id, item.Id)
                .WithParam(x => x.ImageUrl, item.ImageUrl)
                .Navigate();
        }

        public void ViewComments(QiushiItem item)
        {
            NavigateToCommentsView(item);
        }

        public void SentByEmailCommand(QiushiItem item)
        {
            _events.RequestTask<EmailComposeTask>(x =>
                                                      {
                                                          x.Body = item.Content + item.ImageUrl +
                                                                   AppResources.App_Email_Share_Signature;
                                                          x.Subject = AppResources.App_Email_Share_Title;
                                                      });
        }

        public void SentBySmsCommand(QiushiItem item)
        {
            _events.RequestTask<SmsComposeTask>(x => { x.Body = item.Content + AppResources.App_Email_Share_Signature; });
        }


        public void Handle(TaskCompleted<EmailComposeTask> message)
        {
        }

        public void Handle(TaskCompleted<SmsComposeTask> message)
        {
        }

        public void NavigateToNewPostView()
        {
            _navigationService.UriFor<NewPostViewModel>()
                .Navigate();
        }

        public void LaunchPictureViewer(QiushiItem item)
        {
            if (item.ImageUrl == null || !item.ImageUrl.StartsWith("http"))
            {
                MessageBox.Show(AppResources.Ex_No_Picture, AppResources.Ex_Error_Title, MessageBoxButton.OK);
                return;
            }

            _navigationService.UriFor<PicViewModel>()
                .WithParam(x => x.ImageUrl, item.ImageUrl.Replace("small", "large"))
                .Navigate();
        }

        public void ViewPicture(QiushiItem item)
        {
            LaunchPictureViewer(item);
        }
 
    }
}